package test3;

import java.util.PriorityQueue;

public class Solution5 {

    class KthLargest {
        PriorityQueue<Integer> q;
        int k;
        public KthLargest(int k, int[] nums) {
            // 在此处写入代码
            this.q = new PriorityQueue<>(3, (num1, num2) -> num2 - num1);
            this.k = k;
            for (int num: nums) {
                this.add(num);
            }
        }

        public int add(int val) {
            // 在此处写入代码
            if (q.size() < k) {
                q.add(val);
            } else if (q.peek() < val ) {
                q.poll();
                q.add(val);
            }
            return q.peek();
        }
    }

    public int kthSmallest(int[][] matrix, int k) {
        // 在此处写入代码
        if (matrix.length == 0) {
            return -1;
        }
        PriorityQueue<Integer> q = new PriorityQueue<>(k, (v1, v2) -> v2 - v1);

        for(int i = 0; i < matrix.length && i< k; i++) {
            for (int j = 0; j< matrix[0].length && j < k; j++) {
                if (q.size() < k) {
                    q.add(matrix[i][j]);
                } else if (q.peek() > matrix[i][j]){
                    q.poll();
                    q.add(matrix[i][j]);
                }
            }
        }
        return q.peek();

    }
}
